import { defineStore } from "pinia";
import { login, logout, refreshToken } from "../api/auth";
import { message } from "../utils/message";

const STORAGE_KEY = "bearing-shop:user";

const loadSavedState = () => {
  if (typeof window === "undefined") return {};
  try {
    const value = window.localStorage.getItem(STORAGE_KEY);
    return value ? JSON.parse(value) : {};
  } catch (error) {
    console.warn("读取本地用户状态失败", error);
    return {};
  }
};

const persistState = (state) => {
  if (typeof window === "undefined") return;
  try {
    if (!state || (!state.token && !state.partial)) {
      window.localStorage.removeItem(STORAGE_KEY);
      return;
    }
    window.localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({
        token: state.token,
        profile: state.profile,
        partial: state.partial
      })
    );
  } catch (error) {
    console.warn("写入本地用户状态失败", error);
  }
};

const extractAuthPayload = (response) => {
  const body = response?.data ?? response ?? {};
  const payload = body?.data?.data ?? body?.data ?? {};
  return { body, payload };
};

const savedState = loadSavedState();

export const useUserStore = defineStore("user", {
  state: () => ({
    token: savedState.token || null,
    profile: savedState.profile || null,
    partial: savedState.partial || null,
    loading: false,
    error: null
  }),
  getters: {
    isLoggedIn: state => Boolean(state.token?.accessToken),
    username: state => state.profile?.nickname || state.profile?.username || "访客",
    partialAction: state => state.partial?.action || ""
  },
  actions: {
    consumeAuthResponse(response) {
      const { body, payload } = extractAuthPayload(response);
      if (payload.accessToken && payload.partial !== true) {
        this.error = null;
        this.token = {
          accessToken: payload.accessToken,
          refreshToken: payload.refreshToken,
          expires: payload.expires
        };
        this.profile = payload.profile || { nickname: payload.username };
        this.partial = null;
        persistState(this.$state);
        return {
          type: "token",
          payload,
          message: body?.msg || "登录成功"
        };
      }

      if (payload.partial) {
        this.error = null;
        const action =
          payload.partial_action ||
          payload.incompleteAction ||
          payload.context?.partial_action ||
          "";
        const partialData = {
          partial: true,
          action,
          token: payload.accessToken,
          expires: payload.expires,
          context: payload.context || {},
          message: body?.msg || payload.message || "请继续完成后续流程",
          code: body?.code
        };
        this.token = null;
        this.profile = null;
        this.partial = partialData;
        persistState(this.$state);
        return {
          type: "partial",
          payload: partialData,
          message: partialData.message
        };
      }

      if (body?.success === false || (body?.code && body.code !== 200)) {
        throw new Error(body?.msg || "请求失败");
      }

      throw new Error("登录响应不完整");
    },
    async signIn(credentials) {
      this.loading = true;
      this.error = null;
      try {
        const response = await login(credentials);
        const result = this.consumeAuthResponse(response);
        return result.payload;
      } catch (error) {
        this.error = error.message || "登录失败";
        throw error;
      } finally {
        this.loading = false;
      }
    },
    async signOut() {
      try {
        await logout();
      } catch (error) {
        // ignore
      }
      this.reset();
    },
    async refresh() {
      if (!this.token?.refreshToken) return;
      try {
        const response = await refreshToken(this.token.refreshToken);
        const { payload } = extractAuthPayload(response);
        if (payload.accessToken) {
          this.error = null;
          this.token = {
            accessToken: payload.accessToken,
            refreshToken: payload.refreshToken,
            expires: payload.expires
          };
          persistState(this.$state);
          return true;
        }
      } catch (error) {
        this.forceLogout();
      }
    },
    forceLogout(text) {
      this.reset();
      if (text) {
        message.error(text);
      }
    },
    reset() {
      this.token = null;
      this.profile = null;
      this.partial = null;
      persistState(this.$state);
    },
    clearPartial() {
      this.partial = null;
      persistState(this.$state);
    },
    bootstrap() {
      if (this.token?.refreshToken) {
        this.refresh().catch(() => {
          /* 已在 refresh 内处理 */
        });
      }
    },
    persist() {
      persistState(this.$state);
    }
  }
});
